package function;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import entity.ReaderType;
import interfaces.ReaderTypeDao;

import java.sql.Connection;
import java.util.Date;
import java.util.List;

public class ReaderTypeDaoImpl extends BaseDao<ReaderType> implements ReaderTypeDao {

    private static function.ReaderTypeDaoImpl readerTypeDao = null;
    private ReaderTypeDaoImpl() {
    }
    public static function.ReaderTypeDaoImpl getReaderTypeDao(){
        if (readerTypeDao==null) {
            readerTypeDao=new function.ReaderTypeDaoImpl();
        }
            return readerTypeDao;
    }

    @Override
    public void insert(Connection conn, ReaderType readerType) {
        String sql = "INSERT INTO reader_type(type_name,max_borrownum,readerlimit)VALUES(?,?,?)";
        try {
            update(conn, sql, readerType.getTypename(),readerType.getMaxborrownum(),readerType.getReaderlimit());
        } catch (MySQLIntegrityConstraintViolationException throwables) {
            System.out.println("读者类型输入错误，重新输入");
        }
    }

    @Override
    public void deleteById(Connection conn, int id) {
        String sql = "delete from reader_type where id=?";
        try {
            update(conn, sql, id);
            System.out.println("删除成功");
        } catch (MySQLIntegrityConstraintViolationException throwables) {
            System.out.println("该读者类型被使用，无法删除");
        }
    }

    @Override
    public void update(Connection conn, ReaderType readerType) {

        String sql = "UPDATE reader_type SET  type_name=?,max_borrownum=?,readerlimit=? WHERE id=?;";
        try {
            update(conn, sql, readerType.getTypename(), readerType.getMaxborrownum(), readerType.getReaderlimit(),readerType.getId());
            System.out.println("修改成功");
        } catch (MySQLIntegrityConstraintViolationException throwables) {
            System.out.println("修改的读者类型名字重复");
        }

    }

    @Override
    public ReaderType getReaderTypeById(Connection conn, int id) {
        String sql = "select id id,type_name typename,max_borrownum maxborrownum,readerlimit readerlimit from reader_type where id =?";
        ReaderType readerType = getInstance(conn, sql, id);
        return readerType;
    }

    @Override
    public List<ReaderType> getAll(Connection coon) {
        String sql ="select id id,type_name typename,max_borrownum maxborrownum,readerlimit readerlimit from reader_type";
        List<ReaderType> list = getForList(coon, sql);
        return list;
    }

    @Override
    public Long getCount(Connection conn) {
        String sql="select count(*)from reader";
        return getValue(conn,sql);
    }

    @Override
    public Date getMaxBirth(Connection conn) {
        return null;
    }

    public static void main(String[] args) {

    }
}


